<%= form_for [refinery, :admin, @page],
             :url => (refinery.admin_update_page_path(@page.nested_url) if @page.persisted?) do |f| %>

  <%= render '/refinery/admin/error_messages', :object => @page, :include_object_name => true %>

  <%= render '/refinery/admin/locale_picker', :current_locale => Mobility.locale %>

  <div class="field">
    <%= f.label :title %>
    <%= f.text_field :title, :class => "larger widest" %>
  </div>

  <%= render 'form_fields_after_title', :f => f %>

  <div class='field'>
    <%= render 'form_page_parts', :f => f %>
  </div>

  <%= render 'form_advanced_options', :f => f %>

  <%= render '/refinery/admin/form_actions', f: f,
             continue_editing: true,
             delete_title: t('delete', scope: 'refinery.admin.pages'),
             delete_confirmation: t('message', scope: 'refinery.admin.delete', title: @page.title),
             before_cancel_button: submit_tag(
               t('.preview'),
               id: 'preview-button',
               title: 'Preview page',
               name: nil,
               class: 'wymupdate button',
               tooltip: t('.preview_changes'),
               data: { disable_with: false }
             ),
             cancel_url: refinery.admin_pages_path %>

  <%= render 'form_new_page_parts', :f => f if Refinery::Pages.new_page_parts %>
<% end %>

<% content_for :javascripts do %>
  <script>
    $(document).ready(function(){
      page_options.init(
        <%= Refinery::Pages.new_page_parts.to_s %>
        , "<%= refinery.new_admin_page_part_path %>"
        , "<%= refinery.admin_page_parts_path %>"
      );

      $( '#preview-button' ).on( 'click', function(e) {
        e.preventDefault();

        var $form = $(this).parents('form');
        var prev_url = $form.attr('action');
        var prev_target = $form.attr('target') || '';

        $form.attr({
          action: '<%= @page.persisted? ? refinery.pages_admin_preview_page_path(@page.nested_url) : refinery.pages_admin_preview_pages_path %>',
          target: '_blank'
        })

        $form.submit();

        setTimeout(function(){
          $form.attr({
            action: prev_url,
            target: prev_target
          });
        }, 100);
      });
    });
  </script>
<% end %>
